<script setup lang="ts">
import { ref, onBeforeUnmount, shallowRef } from "vue";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { message } from "@/utils/message";
import { uploadImage, uploadVideo } from "@/api/sysupload";
import Motion from "@/views/login/utils/motion";
import ChoiceList from "@/views/question/produce/choice/index.vue";
import ChildList from "@/views/question/produce/child/index.vue";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: "",
    pid: "0",
    type: 0,
    title: "",
    score: 0,
    del: 0,
    question: "",
    description: "",
    addtime: "",
    updatetime: ""
  })
});

const typeData = ref([]);
const questionData0 = ref([
  { id: "A" },
  { id: "B" },
  { id: "C" },
  { id: "D" },
  { id: "E" },
  { id: "F" },
  { id: "G" },
  { id: "H" },
  { id: "I" },
  { id: "J" },
  { id: "K" },
  { id: "L" }
]);
const questionData1 = ref([
  { id: "0", name: "错误" },
  { id: "1", name: "正确" }
]);

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

if (newFormInline.value.pid == "0") {
  typeData.value = [
    { id: 0, name: "判断题" },
    { id: 1, name: "单选题" },
    { id: 2, name: "多选题" },
    { id: 3, name: "案例分析" }
  ];
} else {
  typeData.value = [
    { id: 0, name: "判断题" },
    { id: 1, name: "单选题" },
    { id: 2, name: "多选题" }
  ];
}

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入题目...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const form = new FormData();
        form.append("file", file);
        uploadImage(form)
          .then(res => {
            if (res.errno == 0) {
              message("上传成功", { type: "success" });
              insertFn(res.data.url, res.data.alt, res.data.href);
            } else {
              message("上传失败:" + res.message, { type: "error" });
            }
          })
          .catch(error => {
            message("上传失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        const form = new FormData();
        form.append("file", file);
        uploadVideo(form)
          .then(res => {
            if (res.errno == 0) {
              message("上传成功", { type: "success" });
              insertFn(res.data.url, res.data.poster);
            } else {
              message("上传失败:" + res.message, { type: "error" });
            }
          })
          .catch(error => {
            message("上传失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    }
  }
};

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editorTitle = editorRef.value;
  if (editorTitle != null) {
    editorTitle.destroy();
  }
});
</script>

<template>
  <div>
    <!-----新录入或者判断题没有右边区域------->
    <el-form
      ref="ruleFormRef"
      :model="newFormInline"
      :rules="formRules"
      label-width="82px"
      v-if="newFormInline.id.length == 0 || newFormInline.type == 0"
    >
      <Motion>
        <el-form-item label="题型：" prop="type">
          <el-select
            v-model="newFormInline.type"
            filterable
            placeholder="请选择"
            clearable
            class="!w-[220px]"
            v-if="newFormInline.id.length == 0"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in typeData"
              :key="item.id"
            />
          </el-select>
          <el-select
            v-model="newFormInline.type"
            filterable
            placeholder="请选择"
            clearable
            class="!w-[220px]"
            :disabled="true"
            v-if="newFormInline.id.length > 0"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in typeData"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
      </Motion>
      <Motion>
        <el-form-item label="题目：" prop="title">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="width: 100%; height: 300px; overflow-y: hidden"
            v-model="newFormInline.title"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </el-form-item>
      </Motion>
      <Motion>
        <el-form-item
          label="答案："
          prop="question"
          v-if="newFormInline.type == 0"
        >
          <el-select
            v-model="newFormInline.question"
            filterable
            placeholder="请选择"
            clearable
            class="!w-[220px]"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in questionData1"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
      </Motion>
      <Motion>
        <el-form-item
          label="答案："
          prop="question"
          v-if="newFormInline.type == 1"
        >
          <el-select
            v-model="newFormInline.question"
            filterable
            placeholder="请选择"
            clearable
            class="!w-[220px]"
          >
            <el-option
              :label="item.id"
              :value="item.id"
              v-for="item in questionData0"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
      </Motion>
      <Motion>
        <el-form-item
          label="答案："
          prop="question"
          v-if="newFormInline.type == 2"
        >
          <el-select
            v-model="newFormInline.question"
            filterable
            multiple
            placeholder="请选择"
            clearable
            class="!w-[220px]"
          >
            <el-option
              :label="item.id"
              :value="item.id"
              v-for="item in questionData0"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
      </Motion>
      <Motion>
        <el-form-item
          label="分值："
          prop="score"
          v-if="newFormInline.type != 3"
        >
          <el-input
            v-model="newFormInline.score"
            clearable
            placeholder="请输入分值"
          />
        </el-form-item>

        <el-form-item label="备注：" prop="description">
          <el-input
            type="textarea"
            v-model="newFormInline.description"
            clearable
            placeholder="请输入备注"
          />
        </el-form-item>
      </Motion>
    </el-form>
    <!-----编辑时，判断题，多选题，案例分析题有右边区域显示子内容------->
    <el-card
      shadow="never"
      v-if="newFormInline.id.length > 0 && newFormInline.type > 0"
    >
      <el-row :gutter="24">
        <el-col
          :xs="24"
          :sm="8"
          :md="11"
          :lg="12"
          :xl="12"
          v-motion
          :initial="{
            opacity: 0,
            y: 100
          }"
          :enter="{
            opacity: 1,
            y: 0,
            transition: {
              delay: 200
            }
          }"
        >
          <el-form
            ref="ruleFormRef"
            :model="newFormInline"
            :rules="formRules"
            label-width="82px"
          >
            <Motion>
              <el-form-item label="题型：" prop="type">
                <el-select
                  v-model="newFormInline.type"
                  filterable
                  placeholder="请选择"
                  clearable
                  class="!w-[220px]"
                  v-if="newFormInline.id.length == 0"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    v-for="item in typeData"
                    :key="item.id"
                  />
                </el-select>
                <el-select
                  v-model="newFormInline.type"
                  filterable
                  placeholder="请选择"
                  clearable
                  class="!w-[220px]"
                  :disabled="true"
                  v-if="newFormInline.id.length > 0"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    v-for="item in typeData"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
            </Motion>
            <Motion>
              <el-form-item label="题目：" prop="title">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="width: 100%; height: 300px; overflow-y: hidden"
                  v-model="newFormInline.title"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
                />
              </el-form-item>
            </Motion>
            <Motion>
              <el-form-item
                label="答案："
                prop="question"
                v-if="newFormInline.type == 0"
              >
                <el-select
                  v-model="newFormInline.question"
                  filterable
                  placeholder="请选择"
                  clearable
                  class="!w-[220px]"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    v-for="item in questionData1"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
            </Motion>
            <Motion>
              <el-form-item
                label="答案："
                prop="question"
                v-if="newFormInline.type == 1"
              >
                <el-select
                  v-model="newFormInline.question"
                  filterable
                  placeholder="请选择"
                  clearable
                  class="!w-[220px]"
                >
                  <el-option
                    :label="item.id"
                    :value="item.id"
                    v-for="item in questionData0"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
            </Motion>
            <Motion>
              <el-form-item
                label="答案："
                prop="question"
                v-if="newFormInline.type == 2"
              >
                <el-select
                  v-model="newFormInline.question"
                  filterable
                  multiple
                  placeholder="请选择"
                  clearable
                  class="!w-[220px]"
                >
                  <el-option
                    :label="item.id"
                    :value="item.id"
                    v-for="item in questionData0"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
            </Motion>
            <Motion>
              <el-form-item
                label="分值："
                prop="score"
                v-if="newFormInline.type != 3"
              >
                <el-input
                  v-model="newFormInline.score"
                  clearable
                  placeholder="请输入分值"
                />
              </el-form-item>

              <el-form-item label="备注：" prop="description">
                <el-input
                  type="textarea"
                  v-model="newFormInline.description"
                  clearable
                  placeholder="请输入备注"
                />
              </el-form-item>
            </Motion>
          </el-form>
        </el-col>

        <el-col
          :xs="24"
          :sm="16"
          :md="13"
          :lg="12"
          :xl="12"
          v-motion
          :initial="{
            opacity: 0,
            y: 100
          }"
          :enter="{
            opacity: 1,
            y: 0,
            transition: {
              delay: 200
            }
          }"
        >
          <ChoiceList
            :form-inline="newFormInline"
            v-if="newFormInline.type == 1 || newFormInline.type == 2"
          />
          <ChildList
            :form-inline="newFormInline"
            v-if="newFormInline.type == 3"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
